package net.ib.mtalk.ui.start;

import java.util.List;

import net.ib.mntalk.protocol.Common.AccessToken;
import net.ib.mntalk.protocol.Common.AccountToken;
import net.ib.mntalk.protocol.Common.RequestToken;
import net.ib.mntalk.protocol.Common.UserToken;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.MTalkIntent;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.service.SelecterService;
import net.ib.mtalk.ui.HomeActivity;
import net.ib.mtalk.ui.attachment.emoticon.EmoticonIme;
import net.ib.mtalk.util.MTalkLogWriter;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

/**
 * 이름설정화면
 * 
 * @author urunimi
 * 
 */
public class NameActivity extends Activity {
	
	public static final int HANDLER_ACCOUNT_AUTH = 3;
	
	private EditText editName;
	
	private Context mContext;
	
	private AccountToken mAccountToken;
	private RequestToken mRequestToken;
	private UserToken mUserToken;
	private AccessToken mAccessToken;
	
	private NameController mUiController;
	
	private ProgressDialog mProgressDialog;
	//private final static int MENU_EMOTICON = 0x01;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		
		setContentView(R.layout.activity_name);
		if(getIntent() != null && getIntent().getExtras() != null) {
			Bundle bundle = getIntent().getExtras();
			byte[] accountToken = bundle.getByteArray(MTalkIntent.KEY_ACCOUNT_TOKEN);
			try {
				mAccountToken = AccountToken.parseFrom(accountToken);
				//GlobalPreferences.putMessageToPreferences(mAccountToken);
			} catch (InvalidProtocolBufferMicroException e) {
				MTalkLogWriter.e(e);
			}
		}
		
		editName = (EditText) findViewById(R.id.editName);
//		InputFilter[] filters = new InputFilter[]{new ByteLengthFilter(20, "KSC5601")};
//		editName.setFilters(filters);
		editName.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(editName.getText().toString().trim().length() < 1)
					findViewById(R.id.btn_ok).setEnabled(false);
				else
					findViewById(R.id.btn_ok).setEnabled(true);
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			public void afterTextChanged(Editable s) {
					
			}
		});
		/*InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editName, InputMethodManager.SHOW_IMPLICIT);*/
		
		mUiController = new NameController(mContext, mHandler, mAccountToken);
		mUiController.acquireRequestTokenToServer();
	}
	
	public void onOkClick(View view) {
		if (editName != null && editName.getText().length() > 0 && mAccountToken != null) {
			mUiController.registerUserToServer(mAccountToken, editName.getText().toString());
			mProgressDialog.show();
		}
	}
	
	public void onResume()
	{
		super.onResume();
		SelecterService.setMode(this, SelecterService.Mode.FULL_SELECT);
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		if(mProgressDialog != null)
		{
			mProgressDialog.hide();
			mProgressDialog.dismiss();
		}
		
		new Handler().postDelayed(new Runnable(){
			public void run() 
			{
				ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
				List<ActivityManager.RunningTaskInfo> info = am.getRunningTasks(50);
				for(int i = 0 ; i < info.size() ; i++)
				{
					if(info.get(i).topActivity.getPackageName().equals(getPackageName()))
						return;
				}
				
				SelecterService.setMode(mContext, SelecterService.Mode.MONO_SELECT);
			}}, 300);
	}
	
	public void goToHomeActivity() {
		Intent intent = new Intent(this, HomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("usage", true);
		finish();
		startActivity(intent);
	}
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what) {
				case HandlerMsgConst.HANDLER_UNKNOWN_ERROR :
					Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
					mProgressDialog.hide();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_REQUEST_SUCCESS :
					mRequestToken = (RequestToken) msg.obj;
					Toast.makeText(mContext, "HANDLER_ACQUIRE_REQUEST_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_REQUEST_FAIL :
					Toast.makeText(mContext, "HANDLER_ACQUIRE_REQUEST_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_USER_SUCCESS:
					mUserToken = (UserToken) msg.obj;
					mUiController.acquireAccessTokenToServer(mRequestToken, mUserToken);
					Toast.makeText(mContext, "HANDLER_REGISTER_USER_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_REGISTER_USER_FAIL :
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_REGISTER_USER_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCESS_SUCCESS:
					mAccessToken = (AccessToken) msg.obj;
					GlobalPreferences.putMessageToPreferences(mAccessToken);
					mUiController.authenticateToServer(mAccessToken);
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCESS_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_ACQUIRE_ACCESS_FAIL:
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCESS_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_AUTHENTICATE_SUCCESS:
					MTalkLogWriter.d("SUCCESS TO LOG-IN");
					mUiController.setSvcAgreement();
					postDelayed(new Runnable(){
						public void run() {
							mUiController.addAllContacts();
							mUiController.getAllView();
						}}, 5000);
					goToHomeActivity();
					Toast.makeText(mContext, "HANDLER_AUTHENTICATE_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_AUTHENTICATE_FAIL :
					mProgressDialog.hide();
					Toast.makeText(mContext, "HANDLER_AUTHENTICATE_FAIL", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_SET_SVC_AGREEMENT_SUCCESS:
					Toast.makeText(mContext, "HANDLER_SET_SVC_AGREEMENT_SUCCESS", Toast.LENGTH_SHORT).show();
					break;
				case HandlerMsgConst.HANDLER_SET_SVC_AGREEMENT_FAIL :
					Toast.makeText(mContext, "HANDLER_SET_SVC_AGREEMENT_FAIL", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		}
	};
	
	/*public boolean onCreateOptionsMenu(Menu menu) {
		if(!editName.isFocused())
			return false;
		menu.add(0, MENU_EMOTICON, 10, "Emoticon").setIcon(R.drawable.emoticon_e057);
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()){
			case MENU_EMOTICON :
				emoticonIme.create(mContext, editName).show();
				break;
			default:
				break;
		}
		return super.onMenuItemSelected(featureId, item);
	}*/
}
